package vip.meeet.freemarker;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import freemarker.template.Version;

import java.io.*;
import java.util.HashMap;
import java.util.Map;

/**
 *
 <#if map?exists>
     <#list map?keys as key>
        ${key}---${map[key]}
     </#list>
 </#if>


 */
public class FreemarkerUtil {


    private static final String TEMPLATE_PATH = "D:\\tmp";

    private static final Version VERSION = new Version("2.3.21");

    public static void main(String[] args) throws IOException, TemplateException {
        // step1 创建freeMarker配置实例
        Version version = new Version("2.3.21");
        Configuration configuration = new Configuration(version);
        Writer out;

        // step2 获取模版路径
        configuration.setDirectoryForTemplateLoading(new File(TEMPLATE_PATH));
        // step3 创建数据模型
        Map<String, Object> dataMap = new HashMap<>();
        dataMap.put("cname", "Hello World!");
        // step4 加载模版文件
        Template template = configuration.getTemplate("index.ftl");
        // step5 生成数据
        File docFile = new File("D:\\tmp\\index.html");
        out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(docFile)));
        // step6 输出文件
        template.process(dataMap, out);
    }

    public static String ftl2Html(File templateDir,String fileName,Map<String,Object> datas) throws IOException, TemplateException {
        Configuration configuration = new Configuration(VERSION);
        configuration.setDirectoryForTemplateLoading(templateDir);
        Template template = configuration.getTemplate(fileName);
        StringWriter stringWriter = new StringWriter();
        template.process(datas, stringWriter);
        return stringWriter.toString();
    }

}
